#include "POSIX_Semaphore.hpp"
#include <fcntl.h>
#include <sys/stat.h>
#include <stdexcept>

POSIX_Semaphore::POSIX_Semaphore(const std::string & name)
{
  sem=sem_open(name.c_str(),O_EXCL | O_RDWR);
  if(sem==SEM_FAILED)
    throw std::runtime_error("无法获取POSIX信号量");
  sem_post(sem);
}

POSIX_Semaphore::~POSIX_Semaphore()
{
  sem_close(sem);
}

void POSIX_Semaphore::Lock()
{
  if(sem_wait(sem)==-1)
    throw std::runtime_error("无法给信号量上锁");
}

void POSIX_Semaphore::Unlock()
{
  if(sem_post(sem)==-1)
    throw std::runtime_error("无法给信号量解锁");
}
